import { getData, removeData } from "@/utils/auth.js";
import { config } from "@/utils/uni-config.js";

export const request = (option = {}) => {
	// 请求拦截
	// console.log("请求拦截");
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.BASE_URL + option.url,
			data: option.data || option.params||{},
			method: option.method || "get",
			header: {

				// "authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImMxZWFkYjUwLTg5NTEtNGMxNy04NjFlLTI4ODIwNDFmZGI1ZSIsInVzZXJuYW1lIjoiYWRtaW4ifQ.Uz5BvZlJZ4cKClBnNg3vMLhjVB7LYJg5hGiVvOiDXeDedjsurvP90dnCCCnxQstkyoljoW_RvXdP3Gxdh0UApg"

				// "Authorization": 'Bearer ' + getData("token1"),
				"Authorization": getData("access_token") ? "Bearer "+getData("access_token") : "",
				 'Content-Type': 'application/json'
				// "x-access-token": getData("token")
			},
			timeout: config.TIMEOUT,
			success: (response) => { //成功的回调函数
			// console.log(response,'response');
				if(response.data.code !== 200 && option.verificationReturn !== false) {
					uni.showToast({
						title: response.data.msg,
						icon: "none",
						duration: 4000
					})
				}
				if(response.data.code === 401) {
					uni.showModal({
						title: '提示',
						content: '登录已过期，请重新登录',
						success: function (res) {
							if (res.confirm) {
								removeData("access_token")
								removeData("userInfo")
								// uni.reLaunch({
								// 	url: "/pages/login/login"
								// })
								uni.reLaunch({
									url: "/pages/home/index"
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
				if(response.data.code === 200 || option.verificationReturn === false) {
					resolve(response.data)
				}
                // console.log(response);
			},
			fail: (error) => { //失败的回调函数
				reject(error)
			},
			complete: (info) => { //调用结束的回调函数（调用成功、失败都会执行）
				// console.log(info);
			}
		})
	})
}